const {
  $util,
} = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    list: [],
    hasMore: true,
    directory: [], // 文件夹目录
    id: 0, // 0为根目录 
    title: '文档库',
    scrollId: 'id0',
    imgUrl: $util.getImgUrl(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData(options);
    this.getDirectory();
    this.getList();
    wx.setNavigationBarTitle({
      title: this.data.barTitle && decodeURIComponent(this.data.barTitle) || '文档库',
    });
  },
  getList() {
    $util.request({
      url: 'entry/wxapp/documents.newGetfilelist',
      data: {
        did: this.data.id,
        page: this.data.page,
      },
      showLoading: false,
      success: (res) => {
        let list = res.data;
        if (this.data.page > 1) {
          list = [...this.data.list, ...list];
        }
        this.setData({
          list,
          hasMore: res.data.length !== 0,
          loaded: true,
        });

      },
    });
  },
  // 获取子文件列表
  getChildList(e) {
    const {
      id,
      idx,
      title,
    } = e.currentTarget.dataset;
    let {
      directory,
      id: did,
    } = this.data;
    if (id === did) return;
    if (idx !== undefined) {
      directory.splice(idx, directory.length - idx);
    }
    this.setData({
      id: id,
      title: title,
      page: 1,
      directory,
    }, () => {
      this.getDirectory();
      this.getList();
    });
  },
  // 获取文件目录
  getDirectory() {
    let directory = this.data.directory;
    let item = [{
      id: this.data.id,
      title: this.data.title,
    }];
    directory = [...directory, ...item];
    this.setData({
      directory, 
      scrollId: `id${this.data.id}`,
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore) {
      this.setData({
        page: this.data.page + 1,
      }, () => {
        this.getList();
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      path: '/ws_party_const/pages/document/list',
    };
  },
});